<template>
  <div class="query1-dia">
    <el-dialog :visible.sync="visible">
      <div class="panelWrap query1-container">
        <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
          <div>{{ isEdit ? '修改维保公司备案' : '添加维保公司备案' }}</div>
          <i class="el-icon-close" @click="handleCloseDialog" />
        </div>
        <div class="con flex">
          <div class="conLeft m-l-40">
            <div class="inputLable inputLable1 input2 flex flexac">
              <span class="name texttr"><span class="mustval">*</span>单位名称：</span>
              <el-input v-model="form.name" class="input input1" placeholder="请输入单位名称" />
              <el-button class="locationBtn locaBtn el-icon-location-information" @click="choiceCoordinate=true">定位</el-button>
            </div>
            <div class="inputLable inputLable1 flex flexac">
              <span class="name texttr"><span class="mustval">*</span>统一社会信用代码：</span>
              <el-input v-model="form.socialCreditCode" class="input" placeholder="请输入统一社会信用代码" />
            </div>
            <div class="inputLable inputLable1 flex flexac">
              <span class="name texttr"><span class="mustval">*</span>应急救援电话：</span>
              <el-input v-model="form.rescuePhone" class="input" placeholder="请输入应急救援电话" />
            </div>
            <div class="inputLable inputLable1 flex flexac">
              <span class="name texttr"><span class="mustval">*</span>主要负责人：</span>
              <el-input v-model="form.chargePerson" class="input" placeholder="请输入主要负责人" />
            </div>
            <div class="inputLable inputLable1 flex flexac">
              <span class="name texttr"><span class="mustval">*</span>坐标：</span>
              <el-input class="input coordinateRead" :value="form.getcoordinate" readonly placeholder="请选择坐标" />
            </div>
            <div class="inputLable inputLable1 flex flexac">
              <span class="name texttr"><span class="mustval">*</span>注册地址：</span>
              <el-input v-model="form.address" class="input" placeholder="请输入注册地址" />
            </div>
            <div class="inputLable inputLable1 flex flexac">
              <span class="name texttr"><span class="mustval">*</span>办公地址：</span>
              <el-input v-model="form.officeAddress" class="input" placeholder="请输入办公地址" />
            </div>
            <div class="inputLable wd100 inputLable1 flex ">
              <span class="name texttr"><span class="mustval">*</span>公司介绍：</span>
              <el-input
                v-model="form.introduce"
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 5}"
                resize="none"
                class="markinfo"
                placeholder="请输入公司介绍"
              />
            </div>
          </div>
          <div class="conRight">
            <div class="uploadwrap">
              <div class="titleTip">
                请上传相关证书及申请表
              </div>
              <div class="row flex sanzhengImg">
                <div class="uploadDetails">
                  <div class="">
                    <div class="uploadDetails-title">请上传营业执照扫描件</div>
                    <uploadImg imgtype="businessLicensePicFile" :is-edit="isEdit" :pic-url="form.businImage" @sendImginfo="handleImginfo" />
                  </div>
                </div>
                <div class="uploadDetails">
                  <div class="">
                    <div class="uploadDetails-title pre">请上传备案申请表扫描件<div class="downTem m-l-10" @click="handleDownFile"><span class="iconfont icon-xiazai" />申请表模板下载</div>
                    </div>
                    <uploadImg imgtype="applyTemplateFile" :is-edit="isEdit" :pic-url="form.applyImage" @sendImginfo="handleImginfo" />
                  </div>
                </div>
              </div>
              <div class="titleTip m-t-10">
                请上传特种设备生产许可证或安装改造维修许可证扫描件
              </div>
              <div class="row flex">
                <div class="uploadDetails">
                  <div class="">
                    <span class="uploadDetails-title">许可证</span>
                    <uploadImg imgtype="produceLicensePicFile" :is-edit="isEdit" :pic-url="form.produceImage" @sendImginfo="handleImginfo" />
                  </div>
                </div>
                <div class="uploadDetails">
                  <div class="">
                    <span class="uploadDetails-title">扫描件</span>
                    <uploadImg imgtype="maintainLicensePicFile" :is-edit="isEdit" :pic-url="form.maintainImage" @sendImginfo="handleImginfo" />
                  </div>
                </div>
              </div>
            </div>
            <div class="inputLable wd100 inputLable1 flex flexac">
              <span class="name texttr"><span class="mustval">*</span>许可证编号：</span>
              <el-input v-model="form.licenseCode" class="input" placeholder="请输入许可证编号" />
            </div>
            <div class="inputLable wd100 inputLable1 flex flexac">
              <span class="name texttr"><span class="mustval">*</span>许可项目：</span>
              <div class="flex ">
                <!-- <div v-for="(item,index) in licenseProjectArr" :key="index" class="m-r-25">
                  <el-checkbox v-model="item.check" :label="item.name" :checked="item.check" @change="handleObjtype(item,index)" />
                </div> -->
                <el-checkbox-group v-for="(item, i) in licenseProjectArr" :key="i" v-model="checkList" class="m-r-25" @change="handleObjtype">
                  <el-checkbox :label="item.name" />
                </el-checkbox-group>
              </div>
            </div>
            <div class="inputLable wd100 inputLable1 flex flexac">
              <span class="name texttr"><span class="mustval">*</span>许可证发证机关：</span>
              <el-input v-model="form.licenseIssuingAuthority" class="input" placeholder="请输入许可证编号" />
            </div>

            <div class="inputLable wd100 inputLable1 flex flexac">
              <span class="name texttr"><span class="mustval">*</span>许可证发证日期：</span>
              <el-date-picker v-model="form.licenseIssuingDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" placeholder="请输入许可证编号" />
            </div>

            <div class="inputLable wd100 inputLable1 flex flexac">
              <span class="name texttr"><span class="mustval">*</span>许可证有效期至：</span>
              <el-date-picker v-model="form.licenseExpiryDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" placeholder="请输入许可证编号" />
            </div>
          </div>
        </div>
        <div v-if="form.auditState !== 1" class="flex  footer m-t-30 m-b-30">
          <el-button v-if="!isEdit" class="btn saveBtn el-icon-circle-check m-r-20" @click="handleSave(0)">保 存</el-button>
          <el-button v-else type="success" class="btn el-icon-circle-check m-r-20" @click="handleSave(1)">更 新</el-button>
          <el-button class="clsoeBtn btn el-icon-circle-close" @click="handleCloseDialog">关 闭</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog v-if="choiceCoordinate" class="coo-dialog" style="margin-left: -200px;" :visible.sync="choiceCoordinate">
      <localtionMap class="coordina" />
    </el-dialog>

  </div>
</template>

<script>

import { unitfilingAdd, unitfilingUpload, unitfilingUpdate } from '@/api/maintenance/unitfiling'
import { showNotice, checkMobile } from '@/utils/toolclass'
import uploadImg from '@/components/uploadImg'
import localtionMap from '@/components/localtionMap'
import bus from '@/utils/bus'
import storage from '@/utils/storage'

export default {
  name: 'QueryDialog',
  components: { uploadImg, localtionMap },
  props: {
    value: {
      type: Boolean
    },
    data: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean
    }
  },
  data() {
    return {
      projectStr: '',
      visible: false,
      choiceCoordinate: false,
      form: { ...this.data },
      checkList: [],
      formOrigin: {
        address: '', // 注册地址 -
        applyTemplateFileId: '', // 备案申请表模板文件ID
        auditState: '', // 复核状态
        auditTime: '', // 复核时间
        businessLicensePicId: '', // 营业执照扫描件图片ID
        chargePerson: '', // 主要负责人 -
        crtDate: '', // 提交时间
        id: '', // ID
        introduce: '', // 介绍 -
        latitude: '', // 纬度 -
        licenseCode: '', // 许可证编号 -
        licenseExpiryDate: '', // 许可证有效期 -
        licenseIssuingAuthority: '', // 许可证发证机关 -
        licenseIssuingDate: '', // 许可证发证时间 -
        licenseProject: '', // 许可项目 -
        longitude: '', // 经度 -
        maintainLicensePicId: '', // 安装改造维修许可证图片ID
        name: '', // 备案单位名称 -
        officeAddress: '', // 办公地址 -
        orgId: '', // 机构ID
        produceLicensePicId: '', // 特种设备生产许可证图片ID
        remark: '', // 备注
        rescuePhone: '', // 应急救援电话
        reviewerId: '', // 复核人ID
        socialCreditCode: '', // 统一社会信用代码 -
        version: '', // 版本号
        getcoordinate: '' // 坐标
      },
      maintenance: {},
      mainrenanceType: false,
      licenseProjectArr: [
        {
          id: 0,
          check: false,
          name: '生产'
        },
        {
          id: 1,
          check: false,
          name: '安装'
        },
        {
          id: 2,
          check: false,
          name: '改造'
        },
        {
          id: 3,
          check: false,
          name: '修理'
        }
      ]
    }
  },
  computed: {},
  watch: {
    visible(v) {
      this.$emit('input', v)
    },
    value(v) {
      this.visible = v
    },
    data(v) {
      // console.log(v)
      if (v.id === 0) {
        this.form = { ...this.formOrigin }
      } else {
        this.checkList = [...v.checkList]
        this.form = { ...v }
      }
    }
  },
  created() {
    this.onCloseCoordinate()
    this.onSendCoordinate()
  },
  mounted() {
    this.userInfo = JSON.parse(storage.get('userInfo'))
  },
  methods: {
    // 申请表模版下载
    handleDownFile() {
      const url = '/maintenance/长沙市智慧电梯平台电梯维保单位备案申请表.doc'
      window.location.href = url
    },
    // 字符串拼接
    getText(rows) {
      // console.log(rows)
      for (var i = 0; i < rows.length; i++) {
        if (this.projectStr.search(rows[i]) === -1) {
          this.projectStr += rows[i] + ','
        }
      }
      // 去掉最后一个逗号(如果不需要去掉，就不用写)
      // if (this.projectStr.length > 0) {
      //   this.projectStr = this.projectStr.substr(0, this.projectStr.length)
      // }
      this.form.licenseProject = this.projectStr.substring(0, this.projectStr.lastIndexOf(','))
      // console.log(this.form.licenseProject)
      return this.form.licenseProject
    },
    handleObjtype(val) {
      // console.log(val)
      this.getText(val)
    },
    onSendCoordinate() {
      bus.$on('sendCoordinate', (data) => {
        this.form.longitude = data.lng
        this.form.latitude = data.lat
        this.form.getcoordinate = data.lng + '，' + data.lat
        this.handleCloseCoordinate()
      })
      bus.$on('sendCoordinateAddress', (data) => {
        // console.log('sendCoordinateAddress')
        // console.log(data, data.address)
        // this.form.address = (data.province === undefined ? '' : data.province) + '' + (data.city === undefined ? '' : data.city) + '' + data.title
        this.form.address = data.address
        this.form.officeAddress = (data.province === undefined ? '' : data.province) + '' + (data.city === undefined ? '' : data.city) + '' + (data.title === undefined ? '' : data.title)
        // console.log(this.form.name)
        this.form.name = this.form.name === '' ? (data.title === undefined ? '' : data.title) : this.form.name
      })
    },
    onCloseCoordinate() {
      bus.$on('closeCoordinate', (data) => {
        this.handleCloseCoordinate()
      })
    },
    handleCloseCoordinate() {
      this.choiceCoordinate = false
    },

    handleDelerow() {
      this.maintenanceList.pop()
    },
    handleImginfo(res) {
      // console.log('监听到图片组件返回信息')
      // console.log(res)
      if (res.imgType === 'applyTemplateFile') {
        // this.maintenance.applyTemplateFile=dataURItoBlob(res.base64Val);
        this.form.applyTemplateFile = res.imgfile
      } else if (res.imgType === 'businessLicensePicFile') {
        // this.maintenance.businessLicensePicFile=dataURItoBlob(res.base64Val);
        this.form.businessLicensePicFile = res.imgfile
      } else if (res.imgType === 'maintainLicensePicFile') {
        // this.maintenance.maintainLicensePicFile=dataURItoBlob(res.base64Val);
        this.form.maintainLicensePicFile = res.imgfile
      } else if (res.imgType === 'produceLicensePicFile') {
        // this.maintenance.produceLicensePicFile=dataURItoBlob(rs.base64Val);
        this.form.produceLicensePicFile = res.imgfile
      }
    },
    // handleUpdate() {
    //   simpleViewUpdate(this.addFactory).then((res) => {
    //     if (res.code == '000000') {
    //       showNotice('success', '提示', '保存成功')
    //       this.$emit('handleRefresh')
    //       this.$emit('handleCloseDialog')
    //     }
    //   })
    // },
    handleSave(type) {
      // console.log(this.form.licenseProject)
      this.licenseProjectArr.forEach((item) => {
        if (item.check) {
          this.form.licenseProject = item.name
        }
      })
      if (this.form.name === '') {
        showNotice('error', '提示', '单位名称不能为空')
        return
      }
      if (this.form.socialCreditCode === '') {
        showNotice('error', '提示', '统一社会信用代码不能为空')
        return
      }

      if (this.form.socialCreditCode.length !== 18) {
        showNotice('error', '提示', '统一社会信用代码长度为18位')
        return
      }

      if (this.form.rescuePhone === '') {
        showNotice('error', '提示', '应急救援电话不能为空')
        return
      }
      if (!checkMobile(this.form.rescuePhone)) {
        showNotice('error', '提示', '应急救援电话手机格式不对')
        return
      }

      if (this.form.chargePerson === '') {
        showNotice('error', '提示', '主要负责人不能为空')
        return
      }
      if (this.form.address === '') {
        showNotice('error', '提示', '注册地址不能为空')
        return
      }
      if (this.form.officeAddress === '') {
        showNotice('error', '提示', '办公地址不能为空')
        return
      }

      if (this.form.introduce === '') {
        showNotice('error', '提示', '公司介绍不能为空')
        return
      }

      if (this.form.licenseCode === '') {
        showNotice('error', '提示', '许可证编号不能为空')
        return
      }

      if (this.form.licenseProject === '') {
        showNotice('error', '提示', '许可项目不能为空')
        return
      }
      if (this.form.licenseIssuingAuthority === '') {
        showNotice('error', '提示', '发证机关不能为空')
        return
      }
      if (this.form.licenseIssuingDate === '') {
        showNotice('error', '提示', '许可证发证日期不能为空')
        return
      }
      if (this.form.licenseExpiryDate === '') {
        showNotice('error', '提示', '许可证发证有效期不能为空')
        return
      }

      if (this.form.applyTemplateFile === '') {
        showNotice('error', '提示', '备案申请表模板文件不能为空')
        return
      }
      if (this.form.businessLicensePicFile === '') {
        showNotice('error', '提示', '营业执照扫描件图片不能为空')
        return
      }
      if (this.form.maintainLicensePicFile === '') {
        showNotice('error', '提示', '安装改造维修许可证图片不能为空')
        return
      }

      if (this.form.produceLicensePicFile === '') {
        showNotice('error', '提示', '特种设备生产许可证图片不能为空')
        return
      }
      // console.log(this.form)

      const params = {
        address: this.form.address,
        applyTemplateFileId: this.form.applyTemplateFileId, // 备案申请表模板文件ID
        auditState: this.form.auditState, // 复核状态
        auditTime: this.form.auditTime, // 复核时间
        businessLicensePicId: this.form.businessLicensePicId, // 营业执照扫描件图片ID
        chargePerson: this.form.chargePerson,
        crtDate: this.form.crtDate, // 提交时间
        id: this.form.id,
        introduce: this.form.introduce,
        latitude: this.form.latitude,
        licenseCode: this.form.licenseCode,
        licenseExpiryDate: this.form.licenseExpiryDate,
        licenseIssuingAuthority: this.form.licenseIssuingAuthority,
        licenseIssuingDate: this.form.licenseIssuingDate,
        licenseProject: this.form.licenseProject,
        longitude: this.form.longitude,
        maintainLicensePicId: this.form.maintainLicensePicId, // 安装改造维修许可证图片ID
        name: this.form.name,
        officeAddress: this.form.officeAddress,
        orgId: this.userInfo.orgList[0].id,
        produceLicensePicId: this.form.maintainLicensePicId, // 特种设备生产许可证图片ID
        remark: this.form.remark, // 备注
        rescuePhone: this.form.rescuePhone,
        reviewerId: this.form.reviewerId, // 复核人ID
        socialCreditCode: this.form.socialCreditCode,
        version: this.form.version ? this.form.version : 1
      }
      if (type === 0) {
        this.handleMaintenanceAdd(params)
      } else {
        this.handleUpdate(params)
      }
    },
    handleUpdate(data) {
      unitfilingUpdate(data).then((res) => {
        if (res.code === '000000') {
          showNotice('success', '提示', '更新成功!')
          this.$emit('handleRefresh')
          this.$emit('handleCloseDialog')
          this.handleMaintenanceUpload(data.id, this.form.applyTemplateFile,
            this.form.businessLicensePicFile, this.form.maintainLicensePicFile,
            this.form.produceLicensePicFile
          )
        } else {
          if (res.msg === '失败') {
            showNotice('error', '提示', `更新${res.msg}`)
          } else {
            showNotice('error', '提示', res.msg)
          }
        }
      })
    },
    handleCloseDialog() {
      // console.log('子组件关闭')
      this.$emit('handleCloseDialog')
    },
    handleMaintenanceAdd(data) {
      unitfilingAdd(data).then((res) => {
        if (res.code === '000000') {
          showNotice('success', '提示', '保存成功!')
          this.$emit('handleRefresh')
          this.$emit('handleCloseDialog')
          this.handleMaintenanceUpload(res.data.id, this.form.applyTemplateFile,
            this.form.businessLicensePicFile, this.form.maintainLicensePicFile,
            this.form.produceLicensePicFile
          )
        } else {
          if (res.msg === '失败') {
            showNotice('error', '提示', `保存${res.msg}`)
          } else {
            showNotice('error', '提示', res.msg)
          }
        }
      })
    },
    handleMaintenanceUpload(id, applyTemplateFile, businessLicensePicFile, maintainLicensePicFile, produceLicensePicFile) {
      // console.log(id, applyTemplateFile, businessLicensePicFile, maintainLicensePicFile, produceLicensePicFile)

      const formData = new FormData()
      formData.append('id', id)
      formData.append('applyTemplateFile', applyTemplateFile)
      formData.append('businessLicensePicFile', businessLicensePicFile)
      formData.append('maintainLicensePicFile', maintainLicensePicFile)
      formData.append('produceLicensePicFile', produceLicensePicFile)
      unitfilingUpload(formData).then((res) => {
        if (res.code === '000000') {
          this.$emit('handleRefresh')
          // showNotice('success', '提示', '保存成功!')
          // this.$router.push({path:'/record',query:{obj:res.data}});
        } else {
          // showNotice('error', '提示', res.msg)
        }
      })
    }
  }
}
</script>

<style rel='stylesheet/scss' lang='scss'>
@import "@/styles/addtable.scss";
@import "@/styles/public.scss";

.query1-dia {
  .query1-container {
    .co-map {
      background: #ffffff;
    }
    width: 1220px;
    background: #ffffff;
    margin-left: -400px;
    margin-top: -140px;
    margin-bottom: 40px;
    .el-icon-circle-check:before {
      margin-right: 4px;
    }
    .inputLable .name {
      width: 140px !important;
      letter-spacing: 0px;
    }
    .btn {
      width: 100px;
      height: 40px;
    }
    .input2 {
      margin-left: 4px;
    }
    .el-icon-location-outline:before {
      margin-right: 4px;
    }
    .locaBtn {
      height: 34px;
    }
    .panelWrap .title {
      padding-left: 30px;
    }
    h5 {
      font-size: 15px;
      background-color: #f5f5f5;
    }
    .conLeft {
      width: 40%;
    }
    .conLeft,
    .conRight {
      // flex: 1;
      padding-left: 1%;
      .inputLable {
        margin-top: 30px;
      }
      .panelWrap .inputLable input {
        width: 60%;
      }
    }

    .markinfo {
      width: 48.4% !important;
      border-width: 1px;
      border-color: var(--inputbc);
      border-radius: 3px;
      outline: none;
    }

    .conRight {
      padding-left: 30px;
      border-left: 1px solid #ccc;
      .titleTip {
        padding: 16px 0;
        border-bottom: 1px solid #ddd;
        font-size: 15px;
      }
      font-size: 13px;
      margin: 20px 30px;
      .inputLable {
        margin-top: 20px;
        .name {
          text-align: left !important;
        }
      }
    }
    .uploadDetails-title {
      margin: 15px 0 10px 0;
      display: inline-block;
    }

    .coordinateRead {
      width: 46% !important;
    }
    .footer {
      justify-content: center;
    }
    .downTem {
      cursor: pointer;
      padding: 5px 9px;
      color: #fff;
      background-color: #409eff;
      border-color: #409eff;
      border-radius: 3px;
      font-size: 12px;
      position: absolute;
      right: -144px;
      top: -8px;
    }

    .sanzhengImg {
      .uploadDetails-title {
        margin: 20px 0 10px 0;
      }
    }
  }
}
</style>
